package com.zs.utils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author ZhouShuang
 * @version 17
 * @Title
 * @date 2025/6/11 上午9:43
 */
public class RequestToBean {

    public static <T> T convert(Class<T> clazz, HttpServletRequest request) {
        //获取请求参数
        Map<String, String[]> map = request.getParameterMap();
        //创建对象
        try {
            T obj = clazz.getDeclaredConstructor().newInstance();
            //遍历参数
            for (Map.Entry<String, String[]> entry : map.entrySet()) {
                String key = entry.getKey();
                String[] value = entry.getValue();
                if (key != null && value != null && value.length > 0 && !key.equals("opr")) {
                    //获取属性
                    Field field = clazz.getDeclaredField(key);
                    //获得该属性的setter方法
                    String setter = "set" + key.substring(0, 1).toUpperCase() + key.substring(1);
                    Method method = clazz.getMethod(setter, field.getType());
                    //调用setter方法
                    Object val = parseValue(field.getType(), value);
                    method.invoke(obj, val);
                }
            }
            return obj;
        } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException |
                 NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }

    private static Object parseValue(Class<?> type, String[] value) {
        if (type == String.class) {
            return value[0];
        } else if (type == Integer.class || type == int.class) {
            return Integer.valueOf(value[0]);
        } else if (type == Long.class || type == long.class) {
            return Long.valueOf(value[0]);
        } else if (type == Double.class || type == double.class) {
            return Double.valueOf(value[0]);
        } else if (type == Float.class || type == float.class) {
            return Float.valueOf(value[0]);
        } else if (type == Boolean.class || type == boolean.class) {
            return Boolean.valueOf(value[0]);
        } else {
            return value[0];
        }
    }

}
